package cn.lili.modules.goods.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dos.GoodsHotPopular;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.dos.GoodsSkuHotPopular;
import cn.lili.modules.goods.entity.dto.GoodsHotPopularDTO;
import cn.lili.modules.goods.entity.vos.GoodsVO;
import cn.lili.modules.goods.mapper.GoodsHotPopularMapper;
import cn.lili.modules.goods.service.GoodsHotPopularService;
import cn.lili.modules.goods.service.GoodsService;
import cn.lili.modules.goods.service.GoodsSkuHotPopularService;
import cn.lili.modules.goods.service.GoodsSkuService;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 新品爆款商品表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-02-28
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class GoodsHotPopularServiceImpl extends ServiceImpl<GoodsHotPopularMapper, GoodsHotPopular> implements GoodsHotPopularService {

    private final GoodsSkuService goodsSkuService;

    private final GoodsService goodsService;
    private final GoodsSkuHotPopularService goodsSkuHotPopularService;


    /**
     * 保存新款爆火商品配置
     *
     * @param goodsHotPopularList
     * @return
     */
    @Override
    public ResultMessage<Object> addHotPopularGoodsBatch(List<GoodsHotPopular> goodsHotPopularList) {
        if (CollUtil.isEmpty(goodsHotPopularList)) {
            return ResultUtil.error(400, "参数不可为空");
        }
        log.info("#addHotPopularGoodsBatch# 添加商品,第1步,参数为:{}", JSONArray.toJSONString(goodsHotPopularList));
        List<GoodsHotPopular> filteredGoodsHotPopularList = new ArrayList<>();
        //1,查询sku 2,保存
        for (GoodsHotPopular goodsHotPopularParam : goodsHotPopularList) {
            goodsHotPopularParam.setId(null);
            Goods goods = goodsService.getById(goodsHotPopularParam.getGoodsId());
            if (goods == null) {
                log.info("#addHotPopularGoodsBatch# 添加商品,goods == null , goodsId:{}, continue", goodsHotPopularParam.getGoodsId());
                continue;
            }
            log.info("#addHotPopularGoodsBatch# 添加商品,goods 不是 null , goodsId:{}, 逻辑继续", goodsHotPopularParam.getGoodsId());
            LambdaQueryWrapper<GoodsHotPopular> hotQuery = new LambdaQueryWrapper<>();
            hotQuery.eq(true, GoodsHotPopular::getGoodsId, goodsHotPopularParam.getGoodsId());
            if (this.count(hotQuery) > 0) {
                log.info("#addHotPopularGoodsBatch# 添加商品,this.count(hotQuery) > 0, continue , " );
                continue;
            }

            List<GoodsSku> skuList = goodsSkuService.getGoodsSkuListByGoodsId(goodsHotPopularParam.getGoodsId());
            if (CollUtil.isEmpty(skuList)) {
                log.info("#addHotPopularGoodsBatch# 添加商品,CollUtil.isEmpty(skuList) = true, continue , " );
                continue;
            }

            goodsHotPopularParam.setGoodsName(goods.getGoodsName());
            goodsHotPopularParam.setStoreId(goods.getStoreId());
            goodsHotPopularParam.setStoreName(goods.getStoreName());
            goodsHotPopularParam.setOriginalPrice(goods.getPrice());
            goodsHotPopularParam.setQuantity(goods.getQuantity());
            goodsHotPopularParam.setId(SnowFlake.getIdStr());

            List<GoodsSkuHotPopular> goodsSkuHotPopularListParams = new ArrayList<>();
            LambdaQueryWrapper<GoodsSkuHotPopular> skuhotQuery = new LambdaQueryWrapper<>();
            for (GoodsSku sku : skuList) {
                skuhotQuery.eq(true, GoodsSkuHotPopular::getSkuId, sku.getId());
                if (goodsSkuHotPopularService.count(skuhotQuery) > 0) {
                    continue;
                }
                GoodsSkuHotPopular skuHotPopular = new GoodsSkuHotPopular();
                skuHotPopular.setGoodsId(sku.getGoodsId());
                skuHotPopular.setSkuId(sku.getId());
                skuHotPopular.setGoodsName(sku.getGoodsName());
                skuHotPopular.setStoreId(goods.getStoreId());
                skuHotPopular.setStoreName(goods.getStoreName());
                skuHotPopular.setThumbnail(goods.getThumbnail());
                skuHotPopular.setSortNum(goodsHotPopularParam.getSortNum());
                skuHotPopular.setOriginalPrice(goodsHotPopularParam.getOriginalPrice());
                skuHotPopular.setSettlementPrice(goodsHotPopularParam.getSettlementPrice());
                skuHotPopular.setHotId(goodsHotPopularParam.getId());
                goodsSkuHotPopularListParams.add(skuHotPopular);
                if (goodsHotPopularParam.getSettlementPrice() == null || (goodsHotPopularParam.getSettlementPrice() != null && skuHotPopular.getOriginalPrice() < goodsHotPopularParam.getSettlementPrice())) {
                    goodsHotPopularParam.setSettlementPrice(skuHotPopular.getOriginalPrice());
                    goodsHotPopularParam.setGoodsSkuId(skuHotPopular.getSkuId());
                }
            }
            if (CollUtil.isNotEmpty(goodsSkuHotPopularListParams)) {
                //保存新款爆品
                boolean saveBatchFlag = goodsSkuHotPopularService.saveBatch(goodsSkuHotPopularListParams);
                if (!saveBatchFlag) {
                    throw new ServiceException(ResultCode.HOT_POPULAR_GOODS_ERROR.name());
                }
            }
            filteredGoodsHotPopularList.add(goodsHotPopularParam);
            log.info("#addHotPopularGoodsBatch# 添加商品,参数为:{}", JSONArray.toJSONString(filteredGoodsHotPopularList));
        }
        if (CollUtil.isNotEmpty(filteredGoodsHotPopularList)) {
            //保存商品表
            if (this.saveOrUpdateBatch(filteredGoodsHotPopularList)) {
                return ResultUtil.success();
            }
        } else {
            return ResultUtil.error(400, "没有需要保存的商品");
        }
        return ResultUtil.error();
    }


    /**
     * 删除新品爆款商品
     * @param
     * @return
     */
    @Override
    public ResultMessage<Object> deleteHotPopularGoods(List<GoodsHotPopular> goodsHotPopularList) {
        if (CollUtil.isEmpty(goodsHotPopularList)) {
            return ResultUtil.error(400, "参数不可为空");
        }
        if (baseMapper.deleteBatchIds(goodsHotPopularList) > 0) {
            //用stream方式获取goodsHotPopularList所有的goodsId
            List<String> deleteHotIds = goodsHotPopularList.stream()
                    .filter(Objects::nonNull) // 过滤掉为 null 的对象
                    .map(GoodsHotPopular::getId) // 获取每个 GoodsHotPopular 对象的 goodsId
                    .filter(Objects::nonNull) // 过滤掉为 null 的 goodsId
                    .collect(Collectors.toList()); // 将结果收集到一个新的 List 中
            if (CollUtil.isEmpty(deleteHotIds)) {
                return ResultUtil.error(400, "参数为空,删除失败");
            }
            //删除skuHotPopularList
            LambdaUpdateWrapper<GoodsSkuHotPopular> update = new LambdaUpdateWrapper<>();
            update.in(true, GoodsSkuHotPopular::getHotId, deleteHotIds);
            goodsSkuHotPopularService.remove(update);
            return ResultUtil.success();
        }
        return ResultUtil.error(400, "删除失败");
    }

    /**
     * 更新新品爆款商品信息
     * @param goodsHotpopular
     * @return
     */
    @Override
    public ResultMessage<Object> updateHotPopularGoods(GoodsHotPopular goodsHotpopular) {
        this.checkParams(goodsHotpopular);
        if (baseMapper.updateById(goodsHotpopular) > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error(400, "更新失败");
    }

    /**
     * 检查新品爆款商品参数
     * @param goodsHotpopular
     * @return
     */
    private GoodsHotPopular checkParams(GoodsHotPopular goodsHotpopular) {
        if (goodsHotpopular == null || goodsHotpopular.getId() == null) {
            throw new ServiceException("参数不可为空");
        }
        GoodsHotPopular goodsHotPopular = baseMapper.selectById(goodsHotpopular.getId());
        if (goodsHotPopular == null) {
            throw new ServiceException("该商品已不存在");
        }
        return goodsHotPopular;
    }

    /**
     * 获取新品爆款商品列表
     *
     * @param dto
     * @return
     */
    @Override
    public Page<GoodsHotPopular> getHotPopularGoodsPageList(GoodsHotPopularDTO dto) {
//        Page<GoodsHotPopular> page = baseMapper.selectPage(new Page<>(dto.getPageNumber(), dto.getPageSize()), dto.toQueryWrapper());
        Page<GoodsHotPopular> page = baseMapper.getHotPopularGoodsPageList(new Page<>(dto.getPageNumber(), dto.getPageSize()), dto);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(e -> {
                GoodsSku goodsSku = goodsSkuService.getById(e.getGoodsSkuId());
                if (null != goodsSku && null != goodsSku.getGreenScore()) {
                    e.setGreenScore(goodsSku.getGreenScore());
                }
            });
        }
        return page;
    }

    /**
     * APP分页获取新品爆款商品列表
     * @param dto
     * @return
     */
    @Override
    public Page<GoodsVO> getHotPopularGoodsAppList(GoodsHotPopularDTO dto) {
        Page<GoodsVO> page = baseMapper.getHotPopularGoodsAppList(new Page<>(dto.getPageNumber(), dto.getPageSize()), dto);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            page.getRecords().stream().forEach(e -> {
                e.setBuyCount(e.getBuyCount() > 0 ? e.getBuyCount() : 0);
                GoodsSku goodsSku = goodsSkuService.getById(e.getGoodsSkuId());
                if (null != goodsSku && null != goodsSku.getGreenScore()) {
                    e.setGreenScore(goodsSku.getGreenScore());
                }
            });
        }
        return page;
    }
}
